package com.travel.travelServer.controller;

import com.travel.travelServer.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileUploadController {

    @Value("${uploads.dir}")
    private String UPLOAD_DIR;

    @Value("${uploads.path}")
    private String UPLOAD_PATH;

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 创建上传目录（如果不存在）
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件保存路径
            Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());

            // 保存文件到本地
            Files.write(path, file.getBytes());

            return AjaxResult.success(UPLOAD_PATH + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        }
    }
}
